package convert.converter;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.opencsv.CSVWriter;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class json_to_csv {

    public static void main(String[] args) {
        String jsonFilePath = "src/resource/json/output.json";
        String csvFilePath = "src/resource/csv/output.csv";

        convertJSONToCSV(jsonFilePath, csvFilePath);
    }

    public static void convertJSONToCSV(String jsonFilePath, String csvFilePath) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            File jsonFile = new File(jsonFilePath);
            List<Map<String, String>> dataList = objectMapper.readValue(jsonFile, new TypeReference<List<Map<String, String>>>() {});

            CSVWriter csvWriter = new CSVWriter(new FileWriter(csvFilePath));
            List<String> headers = new ArrayList<>();

            if (!dataList.isEmpty()) {
                headers.addAll(dataList.get(0).keySet());
                csvWriter.writeNext(headers.toArray(new String[0]));

                for (Map<String, String> dataMap : dataList) {
                    List<String> rowData = new ArrayList<>();
                    for (String header : headers) {
                        rowData.add(dataMap.get(header));
                    }
                    csvWriter.writeNext(rowData.toArray(new String[0]));
                }
            }

            csvWriter.close();
            System.out.println("JSON to CSV conversion completed successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
